import React, {Suspense, useEffect , useState} from "react";
import {Route, Routes, useNavigate, useParams, useSearchParams, useLocation, useMatch, Navigate} from 'react-router-dom';
import routes from "./routes";
import store from '../store/index'
import action from '../store/action'
import {Mask, DotLoading, Toast} from "antd-mobile";


const isCheckLogin = (path) => {
    //  1、拿store中的用户信息
    let { user :{info}} = store.getState(),
        checkList = ['/personal', '/store', '/update'];
    // 无用户信息 && 跳转的地址是需要用户信息的页面
    return !info && checkList.includes(path)
}

// 渲染内容的特殊处理(可以在此处做一些登录权限校验...)
const Element = function Element(props) {
    let { component: Component, path ,meta} = props
    let [_, setRandom] = useState(0);
    let isShow = !isCheckLogin(path) //用户信息或者是否需要用户信息
    // 跳转前登录校验
    useEffect(()=>{
        if(isShow) return
        ( async() => {
            // 获取用户信息
            let  infoAction = await action.user.getUserInfo()
            if(!infoAction.info.name){
                Toast.show({
                    icon:'fail',
                    content:'请先登录'
                });
                return <Navigate to={{
                    pathname: '/login' ,
                    search:`?/to=${path}`
                }}/>
            }
            //有用户信息，说明是登录状态，派发任务把信息存储到容器中
            // infoAction = { type : ... , info: ...}
            store.dispatch(infoAction)
            setRandom(+new Date())
        })()
    })

    // 修改页面title
      let  { title = "知乎日报-WebApp" } = meta || {},

        //把路由信息传递给组件，函数组件跟类组件都可以使用props来获取路由信息
        options = {
            navigate: useNavigate(),
            params: useParams(),
            query: useSearchParams()[0],
            location: useLocation(),
            match: useMatch(path)
        };

    // 修改网页title
    document.title = title

    return <>
        {
            isShow ?
                <Component {...options} /> :
                <Mask visible={true}>
                    <DotLoading color="white" />
                </Mask>

        }
    </>


};

// 递归创建路由规则
const createRoute = function createRoute(routes) {
    return <>
        {routes.map((item, index) => {
            return <Route key={index} path={item.path} element={<Element {...item} />}>
                {item.children ? createRoute(item.children) : null}
            </Route>;
        })}
    </>;
};

// 路由表管控
const RouterView = function RouterView() {
    return <Suspense fallback={
        <Mask visible={true} opacity="thick">
            <DotLoading color="white"/>
        </Mask>}>
        <Routes>
            {createRoute(routes)}
        </Routes>
    </Suspense>;
};
export default RouterView;
